package com.example.comsumer.client;


import com.rpctest.myrpc.common.RpcRequest;
import com.rpctest.myrpc.common.RpcResponse;
import com.rpctest.myrpc.common.User;
import com.rpctest.myrpc.serialize.Serializer;
import com.rpctest.myrpc.serialize.SerializerImpl.SerializerImpl;

import java.io.*;
import java.net.Socket;

public class RPCNetTransport {

    String host;
    int port;
    private Serializer serializerInstance;


    public RPCNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private Socket newSocket(){
        System.out.println("begin create connect  ");

        Socket socket = null;
        try{
            socket = new Socket(host,port);
        }catch (Exception e){
            throw new RuntimeException("build connect failed");
        }
        return socket;
    }

    public Object send (RpcRequest request){
        Socket socket = null;
        InputStream in;
        OutputStream out;
        try{
            socket = newSocket();
            //序列化
            serializerInstance = SerializerImpl.class.getConstructor().newInstance();
            byte[] returnRes = serializerInstance.serialize(request);
            out = socket.getOutputStream();
            out.write(returnRes);
            out.flush();
            byte[] recv = new byte[1024];
            in = socket.getInputStream();
            in.read(recv);
            String requestStr = new String(recv);
            //反序列化
            RpcResponse res = (RpcResponse) serializerInstance.deserialize(recv, RpcResponse.class);
//            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
//            outputStream.writeObject(request);
//            outputStream.flush();
//
//            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
//            Object result = inputStream.readObject(); // 反序列化得到结果
//            inputStream.close();
//            outputStream.close();

//            System.out.println(res.toString());
            out.close();
            in.close();
            return res.getResult();
//            return  new User();
//            return Object.class;
        }catch (Exception e){
            throw new RuntimeException("send request exception:" + e);
        }finally {

            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}